package org.riahispano.twitterds.services.listener.impl;

import org.apache.log4j.Logger;
import org.riahispano.twitterds.domain.LastMessage;
import org.riahispano.twitterds.services.TwitterTimeLineService;
import org.riahispano.twitterds.services.command.TwitterPollingCommand;
import org.riahispano.twitterds.services.listener.TwitterPollingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jms.ConnectionFactory;
import javax.jms.Topic;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: ecamacho
 * riahispano 2010
 */
@Service("twitterPollingService")
public class TwitterPollingServiceImpl implements TwitterPollingService {

    private static final Logger logger = Logger.getLogger( TwitterPollingServiceImpl.class );

    private Map<String, TwitterPollingCommand> pollers;

    @Autowired
    private Topic topic;

    @Autowired
    private ConnectionFactory factory;

    @Autowired
    private TwitterTimeLineService timeLineService;


    public TwitterPollingServiceImpl( ) {
        pollers = new HashMap<String, TwitterPollingCommand>( );
    }



    public void onMessage(LastMessage message) {
        logger.debug("Received message: " + message );
        if( !pollers.containsKey( message.getUser() ) ) {
            logger.debug("New user, starting polling");
            TwitterPollingCommand command = new TwitterPollingCommand( message, topic,
                    factory, timeLineService );
            pollers.put( message.getUser(), command );
            command.execute();           
        }

    }
}
